//
//  RoutePlanViewController.m
//  CarLifes
//
//  Created by yu on 2017/6/30.
//  Copyright © 2017年 jpas. All rights reserved.
//

#import "RoutePlanViewController.h"

#import "NavPointAnnotation.h"
#import "NaviViewController.h"
#import "WalkNaviViewController.h"
#import "SelectableOverlay.h"

#import "RouteView.h"

#import "PreferenceView.h"
#import "KLCPopup.h"
#import "SpeechSynthesizer.h"

#import "MRProgressOverlayView.h"
#import "SelectableTrafficOverlay.h"
#import "LocationManager.h"

@interface RoutePlanViewController ()<
AMapNaviDriveManagerDelegate,DriveNaviDelegate,AMapNaviWalkManagerDelegate,WalkNaviDelegate,SelectNaviRouteDelegate>

@property (nonatomic, strong) UIButton *preferenceBtn;
@property (nonatomic, strong) UISegmentedControl *segment;
@property (nonatomic, strong) AMapNaviPoint *startPoint;
@property (nonatomic, strong) AMapNaviPoint *endPoint;
@property (nonatomic, strong) AMapNaviPoint *mStartPoint;
@property (nonatomic, strong) NSMutableArray *routeIndicatorInfoArray;
@property (nonatomic, strong) KLCPopup *popup;
@property (nonatomic, strong) PreferenceView *preferenceView;
@property (nonatomic, strong) RouteView *routeView;
@property (nonatomic, strong) MRProgressOverlayView *progressView;
@property (nonatomic, assign) BOOL needWalkRoutePlan;

@end

#define kRoutePlanInfoViewHeight    130.f
#define kRouteIndicatorViewHeight   70.f
#define kCollectionCellIdentifier   @"kDriveCellIdentifier"

@implementation RoutePlanViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    //[self setLeftImageNamed:@"back_gray" action:@selector(returnAction)];
    
    [self initMapView];
    
    [self initMyLocation];
    
    [self configSubviews];
    
    // 驾车导航管理类
    [self initDriveManager];
    // 步行导航管理类
    [self initWalkManager];
    // 初始化线路指示器
    [self initRouteIndicatorView];
    
    self.mapView.sd_resetNewLayout
    .leftEqualToView(self.view)
    .rightEqualToView(self.view)
    .topEqualToView(self.view)
    .bottomSpaceToView(self.routeView, 0);
    
    self.needWalkRoutePlan = NO;

#warning 测试，临时从这里调用！！！！！
//    [self initProperties];
//    [self driveRouteHandle];

}

- (void)initMyLocation {
    [LocationManager getLocationInfo:^(double lat, double lng, AMapLocationReGeocode *reGeocode) {
        [LocationManager stopUpdatingLocation];
        
        self.mStartPoint = [AMapNaviPoint locationWithLatitude:lat longitude:lng];
        ///<1>.初始化起点和终点
        [self initProperties];
        ///<2>.添加起点和终点标注点
        [self initAnnotations];
        ///<3>.路线规划
        if (!self.needWalkRoutePlan) {
            [self calculateDriveRoute:NO];
        } else {
            [self calculateWalkRoute:YES];
        }
    }];
}

- (UISegmentedControl *)segment
{
    if (!_segment)
    {
        _segment = [[UISegmentedControl alloc] initWithItems:@[@"驾车",@"步行"]];
        _segment.sd_layout.heightIs(30).widthIs(120);
        _segment.tintColor = kBaseColor;
        _segment.selectedSegmentIndex = 0;
        _segment.layer.masksToBounds = YES;
        [_segment addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    }
    return _segment;
}


- (void)segmentAction:(UISegmentedControl *)segment
{
    switch (segment.selectedSegmentIndex)
    {
        case 0: [self driveRouteHandle]; break;
            
        case 1: [self walkRouteHandle]; break;
            
        default: break;
    }
}

- (void)driveRouteHandle
{
    [self calculateDriveRoute:YES];
    self.preferenceBtn.hidden = NO;
    self.needWalkRoutePlan = NO;
}

- (double)calcDistanceBetweenPoint:(AMapNaviPoint *)pointA andPoint:(AMapNaviPoint *)pointB
{
    MAMapPoint mapPointA = MAMapPointForCoordinate(CLLocationCoordinate2DMake(pointA.latitude, pointA.longitude));
    MAMapPoint mapPointB = MAMapPointForCoordinate(CLLocationCoordinate2DMake(pointB.latitude, pointB.longitude));
    
    return MAMetersBetweenMapPoints(mapPointA, mapPointB);
}

- (void)walkRouteHandle
{
    //double shortestDistance = [_userLocation distanceFromLocation:self.destinationPoint];
    double distance = [self calcDistanceBetweenPoint:self.startPoint andPoint:self.endPoint];
    
    if (distance <= 100000.0)
    {
        [self calculateWalkRoute:YES];
        self.preferenceBtn.hidden = YES;
        self.needWalkRoutePlan = YES;
    }
    else
    {
        UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"目的地过远，建议驾车导航" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [controller addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            self.segment.selectedSegmentIndex = 0;
        }]];

        [self presentViewController:controller animated:YES completion:nil];
    }
}

- (NSMutableArray *)routeIndicatorInfoArray
{
    if (!_routeIndicatorInfoArray) {
        _routeIndicatorInfoArray = [NSMutableArray array];
    }
    return _routeIndicatorInfoArray;
}
#pragma mark - Initalization

- (void)initProperties
{
#warning 临时测试数据！！！！！！！
//    self.startPoint = [AMapNaviPoint locationWithLatitude:40.018217 longitude:116.418767];
    self.startPoint = self.mStartPoint;
    self.endPoint = [AMapNaviPoint locationWithLatitude:self.destinationPoint.coordinate.latitude longitude:self.destinationPoint.coordinate.longitude];
}

- (void)configSubviews
{
    [self setupButton];
    
    [self setupPreferenceView];
    
    [self setupPopupView];
    
    self.navigationItem.titleView = self.segment;

}

- (void)setupPopupView
{
    if (self.popup == nil) {
        self.popup = [KLCPopup popupWithContentView:self.preferenceView
                                           showType:KLCPopupShowTypeSlideInFromBottom
                                        dismissType:KLCPopupDismissTypeSlideOutToBottom
                                           maskType:KLCPopupMaskTypeDimmed
                           dismissOnBackgroundTouch:YES
                              dismissOnContentTouch:NO];
    }
}

- (void)setupPreferenceView
{
    _preferenceBtn = [[UIButton alloc] init];
    [_preferenceBtn addTarget:self action:@selector(preferenceAction) forControlEvents:UIControlEventTouchUpInside];
    [_preferenceBtn setImage:IMAGE_NAMED(@"prefer_setting") forState:UIControlStateNormal];
    [self.view addSubview:_preferenceBtn];
    
    _preferenceBtn.sd_layout
    .leftEqualToView(self.userLocBtn)
    .bottomSpaceToView(self.userLocBtn, 5)
    .widthRatioToView(self.userLocBtn, 1)
    .heightEqualToWidth();
    
    _preferenceView = [[PreferenceView alloc] init];
    [_preferenceView setSize:CGSizeMake(kScreenWidth, kIsIphoneX ? 220 : 200)];
    
    @weakify(self);
    _preferenceView.preferenceBlock = ^{
        @strongify(self);
        [self calculateDriveRoute:YES];
    };
}

- (void)updateSubviews
{
    self.userLocBtn.sd_layout
    .bottomSpaceToView(_routeView, 8);
    [self.userLocBtn updateLayout];
    
    [self.zoomBtnContainer sd_clearAutoLayoutSettings];
    self.zoomBtnContainer.sd_layout
    .bottomEqualToView(self.userLocBtn);
    [self.zoomBtnContainer updateLayout];
}

- (void)calculateDriveRoute:(BOOL)show
{
    [[AMapNaviDriveManager sharedInstance] calculateDriveRouteWithStartPoints:@[self.startPoint] endPoints:@[self.endPoint] wayPoints:nil drivingStrategy:[self.preferenceView strategyWithMultiple]];
    
    [self.popup dismiss:YES];
    
    if (show) {
        [MBProgressHUD showHUDAddedTo:KEY_WINDOW animated:YES];
    }
}

- (void)calculateWalkRoute:(BOOL)show
{
    [self.walkManager calculateWalkRouteWithStartPoints:@[self.startPoint] endPoints:@[self.endPoint]];
    
    if (show) {
        [MBProgressHUD showHUDAddedTo:KEY_WINDOW animated:YES];
    }
}

#pragma mark - 偏好设置
- (void)preferenceAction
{
    [self.popup showWithLayout:KLCPopupLayoutMake(KLCPopupHorizontalLayoutCenter, KLCPopupVerticalLayoutBottom)];
}

- (void)initDriveManager
{
    //self.mapView.delegate = self;
//    if (self.driveManager == nil)
//    {
        //self.driveManager = [AMapNaviDriveManager sharedInstance];
        [[AMapNaviDriveManager sharedInstance] setDelegate:self];
        [[AMapNaviDriveManager sharedInstance] setAllowsBackgroundLocationUpdates:NO];
        [[AMapNaviDriveManager sharedInstance] setPausesLocationUpdatesAutomatically:NO];
//    }
}

- (void)initWalkManager
{
    if (self.walkManager == nil)
    {
        self.walkManager = [[AMapNaviWalkManager alloc] init];
        [self.walkManager setDelegate:self];
        [self.walkManager setAllowsBackgroundLocationUpdates:NO];
        [self.walkManager setPausesLocationUpdatesAutomatically:NO];
    }
}

- (void)initRouteIndicatorView
{
    if (_routeView == nil) {
        _routeView = [[RouteView alloc] init];
        _routeView.delegate = self;
        //_routeView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_routeView];
        
        _routeView.sd_layout
        .leftEqualToView(self.view)
        .bottomEqualToView(self.view)
        .rightEqualToView(self.view)
        .heightRatioToView(self.view, 0.27);
        
        [_routeView updateLayout];

        _progressView = [MRProgressOverlayView showOverlayAddedTo:_routeView animated:YES];
        _progressView.backgroundColor = [UIColor clearColor];
        _progressView.mode = MRProgressOverlayViewModeIndeterminateSmall;
        _progressView.titleLabelText = @"";
        [_routeView addSubview:_progressView];
    }
}

- (void)initAnnotations
{
    [self.mapView removeAnnotations:self.mapView.annotations];
    
    NavPointAnnotation *beginAnnotation = [[NavPointAnnotation alloc] init];
    [beginAnnotation setCoordinate:CLLocationCoordinate2DMake(self.startPoint.latitude, self.startPoint.longitude)];
    beginAnnotation.title = @"起点";
    beginAnnotation.navPointType = NaviPointAnnotationStart;
    
    [self.mapView addAnnotation:beginAnnotation];
    
    NavPointAnnotation *endAnnotation = [[NavPointAnnotation alloc] init];
    [endAnnotation setCoordinate:CLLocationCoordinate2DMake(self.endPoint.latitude, self.endPoint.longitude)];
    endAnnotation.title = @"终点";
    endAnnotation.navPointType = NaviPointAnnotationEnd;
    
    [self.mapView addAnnotation:endAnnotation];
}

#pragma mark - SelectNaviRouteDelegate
- (void)selectNaviRouteMethodWithRouteId:(NSInteger)routeId
{
    [self selectNaviRouteWithID:routeId];
}

- (void)startGPSNaviAction
{
    if (!self.needWalkRoutePlan)
    {
        NaviViewController *driveVC = [[NaviViewController alloc] init];
        [driveVC setDelegate:self];
        
        //将driveView添加为导航数据的Representative，使其可以接收到导航诱导数据
        [[AMapNaviDriveManager sharedInstance] addDataRepresentative:driveVC.driveView];
        
        [self.navigationController pushViewController:driveVC animated:NO];
        //        [self.driveManager setEmulatorNaviSpeed:120];
        [[AMapNaviDriveManager sharedInstance] startGPSNavi];
    }
    else
    {
        WalkNaviViewController *walkVC = [[WalkNaviViewController alloc] init];
        [walkVC setDelegate:self];
        
        //将driveView添加为导航数据的Representative，使其可以接收到导航诱导数据
        [self.walkManager addDataRepresentative:walkVC.walkView];
        
        [self.navigationController pushViewController:walkVC animated:NO];
        //        [self.walkManager setEmulatorNaviSpeed:120];
        [self.walkManager startGPSNavi];
        
    }
}

#pragma mark - Handle Navi Routes

//- (void)showNaviRoutes
//{
//    if ([[AMapNaviDriveManager sharedInstance].naviRoutes count] <= 0)
//    {
//        return;
//    }
//
//    [self.mapView removeOverlays:self.mapView.overlays];
//    [self.routeIndicatorInfoArray removeAllObjects];
//
//    //将路径显示到地图上
//    for (NSNumber *aRouteID in [[AMapNaviDriveManager sharedInstance].naviRoutes allKeys])
//    {
//        AMapNaviRoute *aRoute = [[[AMapNaviDriveManager sharedInstance] naviRoutes] objectForKey:aRouteID];
//        int count = (int)[[aRoute routeCoordinates] count];
//
//        //添加路径Polyline
//        CLLocationCoordinate2D *coords = (CLLocationCoordinate2D *)malloc(count * sizeof(CLLocationCoordinate2D));
//        for (int i = 0; i < count; i++)
//        {
//            AMapNaviPoint *coordinate = [[aRoute routeCoordinates] objectAtIndex:i];
//            PPLog(@"~~~~~~~~ = %lf",coordinate.latitude);;
//            coords[i].latitude = [coordinate latitude];
//            coords[i].longitude = [coordinate longitude];
//        }
//
//        MAPolyline *polyline = [MAPolyline polylineWithCoordinates:coords count:count];
//
//        SelectableOverlay *selectablePolyline = [[SelectableOverlay alloc] initWithOverlay:polyline];
//        [selectablePolyline setRouteID:[aRouteID integerValue]];
//
//        [self.mapView addOverlay:selectablePolyline];
//
//        free(coords);
//
//#warning 路径计算策略！！
//        //更新CollectonView的信息
//        DriveRouteViewInfo *info = [[DriveRouteViewInfo alloc] init];
//        info.routeID = [aRouteID integerValue];
//        info.contentTitle = [NSString stringWithFormat:@"%@", [[aRoute.routeLabels firstObject] content]];
//        info.timeTitle = [NSString stringWithFormat:@"%ld小时%ld分", (long)aRoute.routeTime/3600,((long)aRoute.routeTime / 60) % 60];
//        info.mileageTitle = [NSString stringWithFormat:@"%.2lf公里",(float)aRoute.routeLength/1000];
//
//        [self.routeIndicatorInfoArray addObject:info];
//    }
//
////    [self.routeIndicatorView reloadData];
//
//    [self.routeView setRoutes:self.routeIndicatorInfoArray];
//
//
//    [self.mapView showAnnotations:self.mapView.annotations edgePadding:UIEdgeInsetsMake(70, 70, 200, 70) animated:YES];
//
//    [self selectNaviRouteWithID:[[self.routeIndicatorInfoArray firstObject] routeID]];
//}

- (void)showNaviRoutes
{
    if ([[AMapNaviDriveManager sharedInstance] .naviRoutes count] <= 0)
    {
        return;
    }
    
    [self.mapView removeOverlays:self.mapView.overlays];
    [self.routeIndicatorInfoArray removeAllObjects];
    //NSMutableArray *allInfoModels = [[NSMutableArray alloc] init];
    //NSDictionary *allTags = [self createRotueTagString];
    
    for (NSNumber *aRouteID in [[AMapNaviDriveManager sharedInstance].naviRoutes allKeys])
    {
        AMapNaviRoute *aRoute = [[[AMapNaviDriveManager sharedInstance] naviRoutes] objectForKey:aRouteID];
        
        //添加带实时路况的Polyline
        [self addRoutePolylineWithRouteID:[aRouteID integerValue]];
        
#warning 路径计算策略！！
        //创建DriveRouteViewInfo
        DriveRouteViewInfo *info = [[DriveRouteViewInfo alloc] init];
        info.routeID = [aRouteID integerValue];
        info.contentTitle = [NSString stringWithFormat:@"%@", [[aRoute.routeLabels firstObject] content]];
        info.timeTitle = [NSString stringWithFormat:@"%ld小时%ld分", (long)aRoute.routeTime/3600,((long)aRoute.routeTime / 60) % 60];
        info.mileageTitle = [NSString stringWithFormat:@"%.2lf公里",(float)aRoute.routeLength/1000];

        [self.routeIndicatorInfoArray addObject:info];
    }
    
    [self.routeView setRoutes:self.routeIndicatorInfoArray];
    
//    [self.mapView showOverlays:self.mapView.overlays edgePadding:UIEdgeInsetsMake(70, 70, 200, 70) animated:YES];
    
//    [self.mapView showAnnotations:self.mapView.annotations edgePadding:UIEdgeInsetsMake(70, 70, 200, 70) animated:YES];
    
    //默认选择第一条路线
    [self selectNaviRouteWithID:[[self.routeIndicatorInfoArray firstObject] routeID]];
}

- (void)addRoutePolylineWithRouteID:(NSInteger)routeID
{
    //用不同颜色表示不同的路况
    [self addRoutePolylineUseStrokeColorsWithRouteID:routeID];
    
    //用不同纹理表示不同的路况
    //[self addRoutePolylineUseTextureImageWithRouteID:routeID];
}


- (void)showWalkNaviRoutes
{
    if (self.walkManager.naviRoute == nil)
    {
        return;
    }
    
    [self.mapView removeOverlays:self.mapView.overlays];
    [self.routeIndicatorInfoArray removeAllObjects];
    
    // 将路径显示到地图上
    AMapNaviRoute *aRoute = self.walkManager.naviRoute;
    int count = (int)[[aRoute routeCoordinates] count];
    
    // 添加路径Polyline
    CLLocationCoordinate2D *coords = (CLLocationCoordinate2D *)malloc(count * sizeof(CLLocationCoordinate2D));
    for (int i = 0; i < count; i++)
    {
        AMapNaviPoint *coordinate = [[aRoute routeCoordinates] objectAtIndex:i];
        coords[i].latitude = [coordinate latitude];
        coords[i].longitude = [coordinate longitude];
    }
    
    MAPolyline *polyline = [MAPolyline polylineWithCoordinates:coords count:count];
    
    SelectableOverlay *selectablePolyline = [[SelectableOverlay alloc] initWithOverlay:polyline];
    
    [self.mapView addOverlay:selectablePolyline];
    free(coords);
    
    // 更新CollectonView的信息
    DriveRouteViewInfo *info = [[DriveRouteViewInfo alloc] init];
    info.contentTitle = [NSString stringWithFormat:@"推荐"];
    info.timeTitle = [NSString stringWithFormat:@"%ld小时%ld分钟", (long)aRoute.routeTime/3600,((long)aRoute.routeTime / 60) % 60];
    info.mileageTitle = [NSString stringWithFormat:@"%.1lf公里",(float)aRoute.routeLength/1000];
    
    [self.routeIndicatorInfoArray addObject:info];
    
//    [self.routeIndicatorView reloadData];
    [self.routeView setRoutes:self.routeIndicatorInfoArray];
    
//    [self.mapView showAnnotations:self.mapView.annotations edgePadding:UIEdgeInsetsMake(70, 70, 200, 70) animated:YES];
    
    [self selectNaviRouteWithID:[[self.routeIndicatorInfoArray firstObject] routeID]];
}


- (void)selectNaviRouteWithID:(NSInteger)routeID {
    // 在开始导航前进行路径选择
    if ([[AMapNaviDriveManager sharedInstance] selectNaviRouteWithRouteID:routeID]){
        [self selecteOverlayWithRouteIDs:routeID];
    } else {
        PPLog(@"路径选择失败!");
    }
}

//- (void)selecteOverlayWithRouteID:(NSInteger)routeID
//{
//    [self.mapView.overlays enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id<MAOverlay> overlay, NSUInteger idx, BOOL *stop)
//     {
//         if ([overlay isKindOfClass:[SelectableOverlay class]])
//         {
//             SelectableOverlay *selectableOverlay = (SelectableOverlay *)overlay;
//
//             /* 获取overlay对应的renderer */
//             MAPolylineRenderer * overlayRenderer = (MAPolylineRenderer *)[self.mapView rendererForOverlay:selectableOverlay];
//
//             if (selectableOverlay.routeID == routeID)
//             {
//                 /* 设置选中状态 */
//                 selectableOverlay.selected = YES;
//
//                 /* 修改renderer选中颜色 */
//                 overlayRenderer.fillColor   = selectableOverlay.selectedColor;
//                 overlayRenderer.strokeColor = selectableOverlay.selectedColor;
//
//                 /* 修改overlay覆盖的顺序 */
//                 [self.mapView exchangeOverlayAtIndex:idx withOverlayAtIndex:self.mapView.overlays.count - 1];
//             } else {
//                 /* 设置选中状态. */
//                 selectableOverlay.selected = NO;
//
//                 /* 修改renderer选中颜色. */
//                 overlayRenderer.fillColor   = selectableOverlay.regularColor;
//                 overlayRenderer.strokeColor = selectableOverlay.regularColor;
//             }
//             // 2020.3.24 打开这行，多段线不显示
//             //[overlayRenderer glRender];
//         }
//     }];
//}

- (void)selecteOverlayWithRouteIDs:(NSInteger)routeID
{
    [self.mapView.overlays enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id<MAOverlay> overlay, NSUInteger idx, BOOL *stop)
     {
         if ([overlay isKindOfClass:[SelectableTrafficOverlay class]])
         {
             SelectableTrafficOverlay *selectableOverlay = (SelectableTrafficOverlay *)overlay;
             
             /* 获取overlay对应的renderer. */
             MAPolylineRenderer *polylineRenderer = (MAPolylineRenderer *)[self.mapView rendererForOverlay:selectableOverlay];
             
             if ([polylineRenderer isKindOfClass:[MAMultiColoredPolylineRenderer class]])
             {
                 MAMultiColoredPolylineRenderer *overlayRenderer = (MAMultiColoredPolylineRenderer *)polylineRenderer;
                 
                 if (selectableOverlay.routeID == routeID)
                 {
                     /* 设置选中状态. */
                     selectableOverlay.selected = YES;
                     
                     /* 修改renderer选中颜色. */
                     NSMutableArray *strokeColors = [[NSMutableArray alloc] init];
                     for (UIColor *aColor in selectableOverlay.polylineStrokeColors)
                     {
                         [strokeColors addObject:[aColor colorWithAlphaComponent:1]];
                     }
                     selectableOverlay.polylineStrokeColors = strokeColors;
                     overlayRenderer.strokeColors = selectableOverlay.polylineStrokeColors;
                     
                     /* 修改overlay覆盖的顺序. */
                     [self.mapView exchangeOverlayAtIndex:idx withOverlayAtIndex:self.mapView.overlays.count - 1];
                     [self.mapView showOverlays:@[overlay] animated:YES];
                 }
                 else
                 {
                     /* 设置选中状态. */
                     selectableOverlay.selected = NO;
                     
                     /* 修改renderer选中颜色. */
                     NSMutableArray *strokeColors = [[NSMutableArray alloc] init];
                     for (UIColor *aColor in selectableOverlay.polylineStrokeColors)
                     {
                         [strokeColors addObject:[aColor colorWithAlphaComponent:0.25]];
                     }
                     selectableOverlay.polylineStrokeColors = strokeColors;
                     overlayRenderer.strokeColors = selectableOverlay.polylineStrokeColors;
                 }
             }
             else if ([polylineRenderer isKindOfClass:[MAMultiTexturePolylineRenderer class]])
             {
                 MAMultiTexturePolylineRenderer *overlayRenderer = (MAMultiTexturePolylineRenderer *)polylineRenderer;
                 
                 if (selectableOverlay.routeID == routeID)
                 {
                     /* 设置选中状态. */
                     selectableOverlay.selected = YES;
                     
                     /* 修改renderer选中颜色. */
                     overlayRenderer.strokeTextureImages = selectableOverlay.polylineTextureImages;
                     
                     /* 修改overlay覆盖的顺序. */
                     [self.mapView exchangeOverlayAtIndex:idx withOverlayAtIndex:self.mapView.overlays.count - 1];
                     [self.mapView showOverlays:@[overlay] animated:YES];
                 }
                 else
                 {
                     /* 设置选中状态. */
                     selectableOverlay.selected = NO;
                     
                     /* 修改renderer选中颜色. */
                     overlayRenderer.strokeTextureImages = @[[UIImage imageNamed:@"custtexture_gray"]];
                 }
             }
         }
     }];
}

- (void)addRoutePolylineUseStrokeColorsWithRouteID:(NSInteger)routeID
{
    //必须选中路线后，才可以通过driveManager获取实时交通路况
    if (![[AMapNaviDriveManager sharedInstance] selectNaviRouteWithRouteID:routeID])
    {
        return;
    }
    
    NSArray <AMapNaviPoint *> *oriCoordinateArray = [[AMapNaviDriveManager sharedInstance] .naviRoute.routeCoordinates copy];
    NSArray <AMapNaviTrafficStatus *> *trafficStatus = [[AMapNaviDriveManager sharedInstance]  getTrafficStatusesWithStartPosition:0 distance:(int)[AMapNaviDriveManager sharedInstance] .naviRoute.routeLength];
    
    NSMutableArray <AMapNaviPoint *> *resultCoords = [[NSMutableArray alloc] init];
    NSMutableArray <NSNumber *> *coordIndexes = [[NSMutableArray alloc] init];
    NSMutableArray <UIColor *> *strokeColors = [[NSMutableArray alloc] init];
    [resultCoords addObject:[oriCoordinateArray objectAtIndex:0]];
    
    //依次计算每个路况的长度对应的polyline点的index
    unsigned int i = 1;
    NSInteger sumLength = 0;
    NSInteger statusesIndex = 0;
    NSInteger curTrafficLength = [[trafficStatus firstObject] length];
    
    for ( ; i < [oriCoordinateArray count]; i++)
    {
        double segDis = [self calcDistanceBetweenPoint:[oriCoordinateArray objectAtIndex:i-1]
                                              andPoint:[oriCoordinateArray objectAtIndex:i]];
        
        //两点间插入路况改变的点
        if (sumLength + segDis >= curTrafficLength)
        {
            if (sumLength + segDis == curTrafficLength)
            {
                [resultCoords addObject:[oriCoordinateArray objectAtIndex:i]];
                [coordIndexes addObject:[NSNumber numberWithInteger:((int)[resultCoords count]-1)]];
            }
            else
            {
                double rate = (segDis==0 ? 0 : ((curTrafficLength - sumLength) / segDis));
                AMapNaviPoint *extrnPoint = [self calcPointWithStartPoint:[oriCoordinateArray objectAtIndex:i-1]
                                                                 endPoint:[oriCoordinateArray objectAtIndex:i]
                                                                     rate:MAX(MIN(rate, 1.0), 0)];
                if (extrnPoint)
                {
                    [resultCoords addObject:extrnPoint];
                    [coordIndexes addObject:[NSNumber numberWithInteger:((int)[resultCoords count]-1)]];
                    [resultCoords addObject:[oriCoordinateArray objectAtIndex:i]];
                }
                else
                {
                    [resultCoords addObject:[oriCoordinateArray objectAtIndex:i]];
                    [coordIndexes addObject:[NSNumber numberWithInteger:((int)[resultCoords count]-1)]];
                }
            }
            
            //添加对应的strokeColors
            [strokeColors addObject:[self defaultColorForStatus:[[trafficStatus objectAtIndex:statusesIndex] status]]];
            
            sumLength = sumLength + segDis - curTrafficLength;
            
            if (++statusesIndex >= [trafficStatus count])
            {
                break;
            }
            curTrafficLength = [[trafficStatus objectAtIndex:statusesIndex] length];
        }
        else
        {
            [resultCoords addObject:[oriCoordinateArray objectAtIndex:i]];
            
            sumLength += segDis;
        }
    }
    
    //将最后一个点对齐到路径终点
    if (i < [oriCoordinateArray count])
    {
        while (i < [oriCoordinateArray count])
        {
            [resultCoords addObject:[oriCoordinateArray objectAtIndex:i]];
            i++;
        }
        
        [coordIndexes removeLastObject];
        [coordIndexes addObject:[NSNumber numberWithInteger:((int)[resultCoords count]-1)]];
    }
    else
    {
        while (((int)[coordIndexes count])-1 >= (int)[trafficStatus count])
        {
            [coordIndexes removeLastObject];
            [strokeColors removeLastObject];
        }
        
        [coordIndexes addObject:[NSNumber numberWithInteger:((int)[resultCoords count]-1)]];
        //需要修改textureImages的最后一个与trafficStatus最后一个一致
        [strokeColors addObject:[self defaultColorForStatus:[[trafficStatus lastObject] status]]];
    }
    
    //添加Polyline
    NSInteger coordCount = [resultCoords count];
    CLLocationCoordinate2D *coordinates = (CLLocationCoordinate2D *)malloc(coordCount * sizeof(CLLocationCoordinate2D));
    for (int k = 0; k < coordCount; k++)
    {
        AMapNaviPoint *aCoordinate = [resultCoords objectAtIndex:k];
        coordinates[k] = CLLocationCoordinate2DMake(aCoordinate.latitude, aCoordinate.longitude);
    }
    
    //创建SelectableTrafficOverlay
    SelectableTrafficOverlay *polyline = [SelectableTrafficOverlay polylineWithCoordinates:coordinates count:coordCount drawStyleIndexes:coordIndexes];
    polyline.routeID = routeID;
    polyline.selected = NO;
    polyline.polylineWidth = 10;
    polyline.polylineStrokeColors = strokeColors;
    
    if (coordinates != NULL)
    {
        free(coordinates);
    }
    
    [self.mapView addOverlay:polyline level:MAOverlayLevelAboveLabels];

}

- (AMapNaviPoint *)calcPointWithStartPoint:(AMapNaviPoint *)start endPoint:(AMapNaviPoint *)end rate:(double)rate
{
    if (rate > 1.0 || rate < 0)
    {
        return nil;
    }
    
    MAMapPoint from = MAMapPointForCoordinate(CLLocationCoordinate2DMake(start.latitude, start.longitude));
    MAMapPoint to = MAMapPointForCoordinate(CLLocationCoordinate2DMake(end.latitude, end.longitude));
    
    double latitudeDelta = (to.y - from.y) * rate;
    double longitudeDelta = (to.x - from.x) * rate;
    
    CLLocationCoordinate2D coordinate = MACoordinateForMapPoint(MAMapPointMake(from.x + longitudeDelta, from.y + latitudeDelta));
    
    return [AMapNaviPoint locationWithLatitude:coordinate.latitude longitude:coordinate.longitude];
}

- (UIColor *)defaultColorForStatus:(AMapNaviRouteStatus)status
{
    switch (status) {
        case AMapNaviRouteStatusSmooth:     //1-通畅-green
            return kRgb(25, 108, 247);
        case AMapNaviRouteStatusSlow:       //2-缓行-yellow
            return [UIColor yellowColor];
        case AMapNaviRouteStatusJam:        //3-阻塞-red
            return [UIColor redColor];
        case AMapNaviRouteStatusSeriousJam: //4-严重阻塞-brown
            return [UIColor colorWithRed:160/255.0 green:8/255.0 blue:8/255.0 alpha:1];
        default:                            //0-未知状态-blue
            return [UIColor colorWithRed:26/255.0 green:166/255.0 blue:239/255.0 alpha:1];
    }
}

#warning about navi drive!!!
#pragma mark - AMapNaviDriveManager Delegate

- (void)driveManager:(AMapNaviDriveManager *)driveManager error:(NSError *)error
{
    [MBProgressHUD hideHUDForView:KEY_WINDOW];
    [MBProgressHUD showToast:error.description];
    PPLog(@"error:{%ld - %@}", (long)error.code, error.localizedDescription);
}

//TODO:规划路线成功的回调
- (void)driveManagerOnCalculateRouteSuccess:(AMapNaviDriveManager *)driveManager
{
    [MBProgressHUD hideHUDForView:KEY_WINDOW];
    
    [self.progressView hide:YES];
    
    ///<2>. 计算路线成功后显示路径
    [self showNaviRoutes];
    
    ///<3>. 更新子控件布局
    [self updateSubviews];
}

- (void)dealloc
{
    [[AMapNaviDriveManager sharedInstance] stopNavi];
//    [[AMapNaviDriveManager sharedInstance] removeDataRepresentative:self.driveView];
    [[AMapNaviDriveManager sharedInstance] setDelegate:nil];
    
    BOOL success = [AMapNaviDriveManager destroyInstance];
    PPLog(@"单例是否销毁成功 : %d",success);
}

- (void)driveManager:(AMapNaviDriveManager *)driveManager onCalculateRouteFailure:(NSError *)error
{
    [MBProgressHUD hideHUDForView:KEY_WINDOW];
    PPLog(@"onCalculateRouteFailure:{%ld - %@}", (long)error.code, error.localizedDescription);
}

- (void)driveManager:(AMapNaviDriveManager *)driveManager didStartNavi:(AMapNaviMode)naviMode
{
    PPLog(@"didStartNavi");
}

- (void)driveManagerNeedRecalculateRouteForYaw:(AMapNaviDriveManager *)driveManager
{
    PPLog(@"needRecalculateRouteForYaw");
}

- (void)driveManagerNeedRecalculateRouteForTrafficJam:(AMapNaviDriveManager *)driveManager
{
    PPLog(@"needRecalculateRouteForTrafficJam");
}

- (void)driveManager:(AMapNaviDriveManager *)driveManager onArrivedWayPoint:(int)wayPointIndex
{
    PPLog(@"onArrivedWayPoint:%d", wayPointIndex);
}

- (BOOL)driveManagerIsNaviSoundPlaying:(AMapNaviDriveManager *)driveManager
{
    return [[SpeechSynthesizer sharedSpeechSynthesizer] isSpeaking];
}

- (void)driveManager:(AMapNaviDriveManager *)driveManager playNaviSoundString:(NSString *)soundString soundStringType:(AMapNaviSoundType)soundStringType
{
    PPLog(@"playNaviSoundString:{%ld:%@}", (long)soundStringType, soundString);
    [[SpeechSynthesizer sharedSpeechSynthesizer] speakString:soundString];
}

- (void)driveManagerDidEndEmulatorNavi:(AMapNaviDriveManager *)driveManager
{
    PPLog(@"didEndEmulatorNavi");
}

- (void)driveManagerOnArrivedDestination:(AMapNaviDriveManager *)driveManager
{
    PPLog(@"onArrivedDestination");
}

#pragma mark - DriveNaviView Delegate

- (void)driveNaviViewCloseButtonClicked
{
    // 开始导航后不再允许选择路径，所以停止导航
    [[AMapNaviDriveManager sharedInstance] stopNavi];
    
    [[SpeechSynthesizer sharedSpeechSynthesizer] stopSpeak];
    
    [self.navigationController popViewControllerAnimated:NO];
}

#pragma mark - WalkNaviView Delegate

- (void)walkNaviViewCloseButtonClicked
{
    [self.walkManager stopNavi];
    
    [[SpeechSynthesizer sharedSpeechSynthesizer] stopSpeak];
    
    [self.navigationController popViewControllerAnimated:NO];
}

#warning about navi walk!!!!
#pragma mark - AMapNaviWalkManager Delegate

/**
 * @brief 发生错误
 */
- (void)walkManager:(AMapNaviWalkManager *)walkManager error:(NSError *)error
{
    [MBProgressHUD hideHUDForView:KEY_WINDOW];
    PPLog(@"walkError:{%ld - %@}", (long)error.code, error.localizedDescription);
}

/**
 * @brief 步行路径规划成功后的回调函数
 */
- (void)walkManagerOnCalculateRouteSuccess:(AMapNaviWalkManager *)walkManager
{
    [MBProgressHUD hideHUDForView:KEY_WINDOW];
    
    // 计算路线成功后显示路径
    [self showWalkNaviRoutes];
    
    // 更新子控件布局
    [self updateSubviews];
}

/**
 * @brief 步行路径规划失败后的回调函数
 * @param error 错误信息,error.code参照AMapNaviCalcRouteState
 */
- (void)walkManager:(AMapNaviWalkManager *)walkManager onCalculateRouteFailure:(NSError *)error
{
    [MBProgressHUD hideHUDForView:KEY_WINDOW];
    [MBProgressHUD showToast:error.description];
    PPLog(@"walkCalculateRouteFailure:{%ld - %@}", (long)error.code, error.localizedDescription);
}

/**
 * @brief 启动导航后回调函数
 */
- (void)walkManager:(AMapNaviWalkManager *)walkManager didStartNavi:(AMapNaviMode)naviMode
{
    PPLog(@"walkDidStartNavi");
}

/**
 * @brief 偏航后将自动重新路径规划
 */
- (void)walkManagerNeedRecalculateRouteForYaw:(AMapNaviWalkManager *)walkManager
{
    PPLog(@"walkNeedRecalculateRouteForYaw");
}

/**
 * @brief 导航播报信息回调函数
 */
- (void)walkManager:(AMapNaviWalkManager *)walkManager playNaviSoundString:(NSString *)soundString soundStringType:(AMapNaviSoundType)soundStringType
{
    PPLog(@"walkPlayNaviSoundString:{%ld:%@}", (long)soundStringType, soundString);
    [[SpeechSynthesizer sharedSpeechSynthesizer] speakString:soundString];
}

/**
 * @brief 模拟导航到达目的地停止导航
 */
- (void)walkManagerDidEndEmulatorNavi:(AMapNaviWalkManager *)walkManager
{
    PPLog(@"walkDidEndEmulatorNavi");
}

/**
 * @brief 导航到达目的地后的回调函数
 */
- (void)walkManagerOnArrivedDestination:(AMapNaviWalkManager *)walkManager
{
    PPLog(@"walkOnArrivedDestination");
}


#pragma mark - MAMapView Delegate

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[NavPointAnnotation class]])
    {
        static NSString *annotationIdentifier = @"NaviPointAnnotationIdentifier";
        
        MAPinAnnotationView *pointAnnotationView = (MAPinAnnotationView*)[self.mapView dequeueReusableAnnotationViewWithIdentifier:annotationIdentifier];
        if (pointAnnotationView == nil)
        {
            pointAnnotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:annotationIdentifier];
        }
        
        pointAnnotationView.canShowCallout = YES;
        pointAnnotationView.draggable      = NO;
        //pointAnnotationView.centerOffset = CGPointMake(0, -16);
        NavPointAnnotation *navAnnotation = (NavPointAnnotation *)annotation;
        
        if (navAnnotation.navPointType == NaviPointAnnotationStart) {
            //pointAnnotationView.image = IMAGE_NAMED(@"start_point");
            [pointAnnotationView setPinColor:MAPinAnnotationColorGreen];
            
        } else if (navAnnotation.navPointType == NaviPointAnnotationEnd) {
            //pointAnnotationView.image = IMAGE_NAMED(@"end_point");
            [pointAnnotationView setPinColor:MAPinAnnotationColorRed];
        }
        
        return pointAnnotationView;
    }
    return nil;
}

//- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay
//{
//    if ([overlay isKindOfClass:[SelectableOverlay class]])
//    {
//        SelectableOverlay *selectableOverlay = (SelectableOverlay *)overlay;
//        id<MAOverlay> actualOverlay = selectableOverlay.overlay;
//
//        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:(MAPolyline *)actualOverlay];
//
//        polylineRenderer.lineWidth = 8.f;
//        polylineRenderer.strokeColor = selectableOverlay.isSelected ? selectableOverlay.selectedColor : selectableOverlay.regularColor;
//
//        return polylineRenderer;
//    }
//
//    return nil;
//}
- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[SelectableTrafficOverlay class]])
    {
        SelectableTrafficOverlay *routeOverlay = (SelectableTrafficOverlay *)overlay;
        
        if (routeOverlay.polylineStrokeColors && routeOverlay.polylineStrokeColors.count > 0)
        {
            MAMultiColoredPolylineRenderer *polylineRenderer = [[MAMultiColoredPolylineRenderer alloc] initWithMultiPolyline:routeOverlay];
            
            polylineRenderer.lineWidth = routeOverlay.polylineWidth;
            polylineRenderer.lineJoinType = kMALineJoinRound;
            polylineRenderer.strokeColors = routeOverlay.polylineStrokeColors;
            polylineRenderer.gradient = NO;
            polylineRenderer.fillColor = [UIColor redColor];
            
            return polylineRenderer;
        }
        else if (routeOverlay.polylineTextureImages && routeOverlay.polylineTextureImages.count > 0)
        {
            MAMultiTexturePolylineRenderer *polylineRenderer = [[MAMultiTexturePolylineRenderer alloc] initWithMultiPolyline:routeOverlay];
            
            polylineRenderer.lineWidth = routeOverlay.polylineWidth;
            polylineRenderer.lineJoinType = kMALineJoinRound;
            polylineRenderer.strokeTextureImages = routeOverlay.polylineTextureImages;
            
            return polylineRenderer;
        }
    }
    
    return nil;
}

//- (void)returnAction
//{
//    [self.navigationController popViewControllerAnimated:YES];
//}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setWhiteNavigationBar];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self setDefaultNavigationBar];
}


- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
